package com.apes.framework.jpa.config;

import com.apes.framework.jpa.config.vendor.ApesHibernateJpaVendorAdapter;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.bean.compiler.CharSequenceCompilerException;
import com.apes.framework.util.bean.compiler.DynamicEngine;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @author xul
 * @create 2019-01-22 18:28
 */
@Configuration
public class ApesJpaConfiguration {

    @Value("${apes.condition.used:false}")
    private Boolean used;

    private final JpaProperties properties;
    private final DataSource dataSource;
    private JdbcTemplate jdbcTemplate;

    public ApesJpaConfiguration(JdbcTemplate jdbcTemplate, JpaProperties properties) {
        this.jdbcTemplate = jdbcTemplate;
        this.dataSource = jdbcTemplate.getDataSource();
        this.properties = properties;
    }

    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        AbstractJpaVendorAdapter adapter = new ApesHibernateJpaVendorAdapter();
        adapter.setShowSql(this.properties.isShowSql());
        adapter.setDatabase(this.properties.determineDatabase(this.dataSource));
        adapter.setDatabasePlatform(this.properties.getDatabasePlatform());
        adapter.setGenerateDdl(this.properties.isGenerateDdl());
        loadJavaClass();
        return adapter;
    }

    private void loadJavaClass() {
        if(!used) return;
        DynamicEngine engine = DynamicEngine.getInstance();
        Map<String, CharSequence> managedJavaSources = new HashMap<>();
        String sql = "select id, source from ir_java_source";
        List<Map<String, Object>> rows;
        try {
            rows = jdbcTemplate.queryForList(sql);
        } catch (Exception e){
            return;
        }
        rows.stream().forEach(row -> managedJavaSources.put((String) row.get("id"), (String) row.get("source")));
        try {
            if (managedJavaSources.isEmpty()) return;
            Map<String, Class> compiled = engine.compile(managedJavaSources);
            if (compiled != null) compiled.forEach(engine::addClass);
        } catch (CharSequenceCompilerException e) {
            e.printStackTrace();
        }
    }

}
